package 
{
	import assets.FontAssets;
	import authstates.LoginWindow;
	import com.furusystems.dconsole2.DConsole;
	import com.furusystems.logging.slf4as.ILogger;
	import com.furusystems.logging.slf4as.Logging;
	import com.greensock.TweenLite;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.KeyboardEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.media.Sound;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.Timer;
	import mediadisplay.Constants;
	import mediadisplay.MediaArea;
	import mediadisplay.menusystem.Menu;
	import mediadisplay.timeline.ContentTypes;
	import mediadisplay.ui.AdminButton;
	import mediadisplay.viewerarea.ViewerArea;
	
	/**
	 * ...
	 * @author Anders Figenschow
	 */
	public class Main extends Sprite 
	{
		private var sound:Sound;
		public var soundgraph:SoundGraph;
		private var mediaArea:MediaArea;
		public var menu:Menu;
		public var viewerArea:ViewerArea;
		
		private var timer:Timer = new Timer(10, 0);
		private var currentXML:XML;
		
		private var editorContainer:Sprite;
		private var loginState:LoginWindow;
		
		private var allFonts:FontAssets = new FontAssets();
		
		private var loaderLine:Sprite;
		
		public var soundPlayer:SoundPlayer;
		
		private var debug:Boolean = true;
		public static var VIEW_MODE:String = "viewOnly";
		//public static var VIEW_MODE:String = "viewAndEdit";
		private var user:String = "psychofreud";
		private var pass:String = "anders";
		public static const L:ILogger = Logging.getLogger(Main);
		private var printIndex:int;
		private var xmlArray:Array;
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			loginState = new LoginWindow(this);
			addChild(loginState);
			if (debug) loginState.setCredentials(user, pass);
			
			soundPlayer = new SoundPlayer(this);
			addChild(soundPlayer);
			
			editorContainer = new Sprite();
			addChild(editorContainer);
			editorContainer.y = 387;
			
			var rect:Rectangle = new Rectangle(0, 0, 1024, 600);
			scrollRect = rect;
			
			viewerArea = new ViewerArea(this);
			addChild(viewerArea);
			
			drawLoaderLine();
			
			timer.addEventListener(TimerEvent.TIMER, printStuff);
			addChild(DConsole.view);
			
			//changeTune(1, "lol", "Zimboo_Heh.mp3");
			changeTune(2, "Flash On The Beach 2011 Elevator Pitch", "fotb.mp3");
			//changeTune(3, "Presentasjon Inspiria", "empty.mp3");
			
		}
		
		private function printStuff(e:TimerEvent):void 
		{
			trace(xmlArray[printIndex]);
			printIndex++;
			if (printIndex >= xmlArray.length) {
				timer.stop();
			}
		}
		
		public function getSound():Sound {
			return soundPlayer.getSound();
		}
		
		private function drawLoaderLine():void 
		{
			loaderLine = new Sprite;
			addChild(loaderLine);
			loaderLine.graphics.beginFill(0xff5500);
			loaderLine.graphics.drawRect(0, 0, 1024, 10);
			loaderLine.graphics.endFill();
			loaderLine.scaleY = 0;
		}
		
		public function changeTune(id:int, txt:String, url:String):void {
			if (soundgraph) {
				editorContainer.removeChild(soundgraph);
				viewerArea.cleanup();
			}
			
			soundgraph = new SoundGraph(this, url, id);
			soundgraph.addEventListener(SoundGraph.TRACK_LOADED, trackLoadedHandler);
			editorContainer.addChild(soundgraph);
			
			if (menu) addChild(menu);
			
			if (!Constants.LOGGED_IN) {
				soundgraph.hideEditor();
				if (menu) menu.visible = false;
			} else {
				soundgraph.showEditor();
				if (menu) menu.visible = true;
			}
			
			//menu.visible = false;
			//soundgraph.visible = false;
		}
		
		private function trackLoadedHandler(e:Event):void 
		{
			var keypointsLoader:URLLoader = new URLLoader();
			var urlRequest:URLRequest = new URLRequest("http://www.psychofreud.com/subtitler3000/keypoints.php");
			//var urlRequest:URLRequest = new URLRequest("test.xml");
			var urlRequest:URLRequest = new URLRequest("test2.xml");
			keypointsLoader.addEventListener(Event.COMPLETE, keypointsRetrieved);
			keypointsLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			
			var params:URLVariables = new URLVariables();
			params.tune = soundgraph._tuneID;
			keypointsLoader.dataFormat = URLLoaderDataFormat.TEXT;
			urlRequest.data = params;
			urlRequest.method = URLRequestMethod.GET;
			keypointsLoader.load(urlRequest);
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void 
		{
			trace("io error handler! " + e);
		}
		
		private function keypointsRetrieved(e:Event):void 
		{
			var xml:XML = new XML(e.target.data);
			//printOut(xml);
			
			addChild(DConsole.view);
			
			for each (var loop:XML in xml.loop) 
			{
				soundgraph.addLoop(loop.triggerpoint, loop.destination);
				trace("Added loop section at " + loop.triggerpoint + " which loops back to " + loop.destination);
			}
			
			for each (var n:XML in xml.keypoint) 
			{
				var contenttype:String;
				switch(String(n.type)) {
					case "text":
						contenttype = ContentTypes.TEXT_CONTENT;
					break;
					case "video":
						contenttype = ContentTypes.VIDEO_CONTENT;
					break;
					case "image":
						contenttype = ContentTypes.IMAGE_CONTENT;
					break;
					default:
						contenttype = ContentTypes.TEXT_CONTENT;
					break;
				}
				var color:uint;
				if (n.color == null || n.color == "") {
					color = 0xffffff;
				} else {
					color = n.color;
				}
				var ignore:Boolean = false;
				if (int(n.ignore) == 1) ignore = true;
				var interactionTarget:Number = -1;
				if (n.target != "null" && n.target != "" && n.target != null) interactionTarget = Number(n.target);
				soundgraph.addKeypoint(Number(n.start), Number(n.stop), n.content, n.row, contenttype, n.x, n.y, n.z, n.rotationX, n.rotationY, n.rotationZ, n.scale, n.background, color, ignore, interactionTarget);
				//trace("adding keypoint: " + n.start + "-" + n.stop + " '"+n.content+"' of type '" + contenttype + "'");
			}
			soundgraph.start();	
			viewerArea.setMode();
			//loaderDone();
		}
		
		private function printOut(xml:XML):void 
		{
			printIndex = 0;
			xmlArray = new Array();
			for each (var n:XML in xml.keypoint) 
			{
				xmlArray.push(n);
			}
			timer.reset();
			timer.start();
		}
		
		public function getData(username:String, password:String):void 
		{
			var userdata:URLLoader = new URLLoader();
			userdata.addEventListener(Event.COMPLETE, dataResult);
			userdata.load(new URLRequest("http://www.psychofreud.com/subtitler3000/data.php?username=" + username + "&password=" + password));
			//justDoIt();
		}
		
		public function removeLoginState():void {
			removeChild(loginState);
		}
		
		private function justDoIt():void 
		{
			try 
			{
				var userXML:XML = new XML();
				//var userXML:XML = new XML(e.target.data);
				//if (userXML.user == "") {
					//loginFailed();
					//return;
				//}
				loginState.loginSucceeded();
				soundgraph.timelineContent.zoomedTimeline.updateWaveform();
				
				if (menu != null) removeChild(menu);
				
				menu = new Menu(this, "Choose tune here");
				addChild(menu);
				
				menu.add(1, "Zimboo to the rescue", "Zimboo_Heh.mp3");
				menu.add(2, "Flash On The Beach 2011 Elevator Pitch", "fotb.mp3");
				menu.add(3, "Presentasjon Inspiria", "empty.mp3");
				menu.add(4, "Låt nummer 4", "");
				menu.add(5, "Låt nummer 5", "");
				menu.add(6, "Låt nummer 6", "");
				menu.drawMenu();
				menu.x = 0;
				
				if (viewerArea != null) removeChild(viewerArea);
				viewerArea = new ViewerArea(this);
				addChild(viewerArea);
				
				//changeTune(2, "Tarrus Riley Vikings Dubplate", "tarrus_riley_beat_them_VCS_dubplate_mixed.mp3");
				changeTune(2, "Flash On The Beach 2011 Elevator Pitch", "fotb.mp3");
				//changeTune(3, "Presentasjon Inspiria", "empty.mp3");
				
				removeLoginState();
				Constants.LOGGED_IN = true;
				
				soundgraph.showEditor();
				if (menu) menu.visible = true;
				
				Constants.USER_REAL_NAME = userXML.user.name;
				
				Constants.USER_ID = userXML.user.id;
				
				var tunesList:Array = new Array();
				
				for each (var prop:XML in userXML.tunes.tune) {
					var ob:Object = new Object();
					ob.id = prop.id;
					ob.url = prop.url;
					ob.thumbnail = prop.thumbnail;
					tunesList.push(ob);
				}
				
				if (soundgraph) removeChild(soundgraph);
				
				soundgraph = new SoundGraph(this, userXML.tunes.tune[0].url, userXML.tunes.tune[0].id);
				addChild(soundgraph);
				//soundgraph.placeKeypoints(tunesList);
				
			}catch (err:Error)
			{
				trace("nope! " + err.message);
			}			
			
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyTest);
		}
		
		private function keyTest(e:KeyboardEvent):void 
		{
			//trace(e);
			if (e.keyCode == 112) // F1
			{
				soundgraph.visible = !soundgraph.visible;
				menu.visible = !menu.visible;
				//viewerArea.coords.visible = false;
				if (viewerArea.currentMaskSize == 300) {
					viewerArea.drawMask(300);
				} else {
					viewerArea.drawMask(300);
				}
					
				viewerArea.setMask();
			}
		}
		
		private function dataResult(e:Event):void 
		{
			try 
			{
				var userXML:XML = new XML(e.target.data);
				if (userXML.user == "") {
					loginFailed();
					return;
				}
				loginState.loginSucceeded();
				soundgraph.timelineContent.zoomedTimeline.updateWaveform();
				
				if (menu != null) removeChild(menu);
				
				menu = new Menu(this, "Choose tune here");
				addChild(menu);
				
				menu.add(1, "Zimboo to the rescue", "Zimboo_Heh.mp3");
				menu.add(2, "Flash On The Beach 2011 Elevator Pitch", "fotb.mp3");
				menu.add(3, "Presentasjon Inspiria", "empty.mp3");
				menu.add(4, "Låt nummer 4", "");
				menu.add(5, "Låt nummer 5", "");
				menu.add(6, "Låt nummer 6", "");
				menu.drawMenu();
				menu.x = 0;
				
				if (viewerArea != null) removeChild(viewerArea);
				viewerArea = new ViewerArea(this);
				addChild(viewerArea);
				
				//changeTune(2, "Tarrus Riley Vikings Dubplate", "tarrus_riley_beat_them_VCS_dubplate_mixed.mp3");
				changeTune(2, "Flash On The Beach 2011 Elevator Pitch", "fotb.mp3");
				//changeTune(3, "Presentasjon Inspiria", "empty.mp3");
				
				removeChild(loginState);
				Constants.LOGGED_IN = true;
				
				soundgraph.showEditor();
				if (menu) menu.visible = true;
				
				Constants.USER_REAL_NAME = userXML.user.name;
				
				Constants.USER_ID = userXML.user.id;
				
				var tunesList:Array = new Array();
				
				for each (var prop:XML in userXML.tunes.tune) {
					var ob:Object = new Object();
					ob.id = prop.id;
					ob.url = prop.url;
					ob.thumbnail = prop.thumbnail;
					tunesList.push(ob);
				}
				
				if (soundgraph) removeChild(soundgraph);
				
				soundgraph = new SoundGraph(this, userXML.tunes.tune[0].url, userXML.tunes.tune[0].id);
				addChild(soundgraph);
				//soundgraph.placeKeypoints(tunesList);
				
			}catch (err:Error)
			{
				trace("nope! " + err.message);
			}
		}
		
		private function loginFailed():void 
		{
			loginState.loginFailed();
		}
		
		public function setText(txt:String):void {
			soundgraph.timelineContent.mediaArea.setText(txt);
		}
		
		public function loaderProgress(percentage:Number):void 
		{
			TweenLite.to(loaderLine, 0.3, { scaleY:percentage } );
		}
		public function loaderDone():void {
			trace("loader done!");
			loaderLine.scaleX = 0;
			//viewerArea.setMode();
		}
	}
	
}